#pragma once

#include "comm/my_defs.h"
#include "comm/my_queue.h"
#include "comm/my_rbtree.h"
#include "comm/my_thread_base.h"

typedef struct my_event_s my_event_t;

typedef void(*my_event_handler_t)(my_event_t *event);

struct my_event_s {
    void                *data;
    my_event_handler_t  handler;

    my_rbtree_node_t    timer;
    my_queue_t          queue;

    // timer task exec time. msecond
    int64_t             time_key;

    // enabled read event or write event
    unsigned            active:1;
    // write event or read event
    unsigned            write:1;
    // wheter the event is ready
    unsigned            ready:1;
    // current event has error.
    unsigned            error:1;
    // wheter to add to timer rbtree
    unsigned            timer_set:1;
    // timer expired
    unsigned            timedout:1;
};

static inline int
my_event_timer_cmp(my_rbtree_node_t *a, my_rbtree_node_t *b) {
    my_event_t *aevent =
        (my_event_t *)((char *)a - offsetof(my_event_t, timer));
    my_event_t *bevent =
        (my_event_t *)((char *)b - offsetof(my_event_t, timer));

    if (aevent->time_key == bevent->time_key) {
        return 0;
    }

    return aevent->time_key > bevent->time_key ? 1 : -1;
}

typedef struct my_dispatch_event_s my_dispatch_event_t;

typedef void(*my_dispatch_handler_t)(my_dispatch_event_t *dispatch_event);

struct my_dispatch_event_s {
    my_thread_base_t        *setup_thread;
    void                    *data;
    void                    *save_data;
    my_dispatch_handler_t   handler;

    my_queue_t              queue;
};